package com.demo.springBoot2.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.demo.springBoot2.entity.CampusRingtone;
import com.demo.springBoot2.entity.dto.CampusRingtoneDTO;
import com.demo.springBoot2.entity.vo.CampusRingtoneVO;
import com.demo.springBoot2.mapper.CampusRingtoneMapper;
import com.demo.springBoot2.music.TtsMusicUtil;
import com.demo.springBoot2.service.ICampusRingtoneService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 校园铃声 服务实现类
 * </p>
 *
 * @author wuHua·pl
 * @since 2024-04-11
 */
@Slf4j
// 声明CampusRingtoneServiceImpl类，它继承了ServiceImpl类，并实现了ICampusRingtoneService接口
@Service
public class CampusRingtoneServiceImpl extends ServiceImpl<CampusRingtoneMapper, CampusRingtone> implements ICampusRingtoneService {
    // 自动装配TtsMusicUtil的bean实例
    @Autowired
    private TtsMusicUtil ttsMusicUtil;
    // 自动装配CampusRingtoneMapper的bean实例
    @Autowired
    private CampusRingtoneMapper campusRingtoneMapper;
    // 重写ICampusRingtoneService接口中的selectRingtoneByRingPeriod方法
    @Override
    public CampusRingtoneDTO selectRingtoneByRingPeriod(CampusRingtone campusRingtone) {
        // 创建一个CampusRingtoneDTO对象，用于传输数据
        CampusRingtoneDTO campusRingtoneDTO = new CampusRingtoneDTO();
        // 调用mapper的selectRingtoneByRingPeriod方法，根据传入的campusRingtone条件查询数据库，获取结果
        CampusRingtone campusRingtone1 = campusRingtoneMapper.selectRingtoneByRingPeriod(campusRingtone);
        // 如果查询到的campusRingtone1对象的铃声路径不为空
        if (campusRingtone1.getRingtonePath() != null) {
            // 使用BeanUtil工具类将campusRingtone1的属性复制到campusRingtoneDTO中
            BeanUtil.copyProperties(campusRingtone1, campusRingtoneDTO);
            // 返回填充了属性的campusRingtoneDTO对象
            return campusRingtoneDTO;
        }
        // 如果铃声路径为空，则调用ttsMusicUtil的syntheticAudio方法合成音频，并获取生成的URL
        String url = ttsMusicUtil.syntheticAudio(campusRingtone1.getRingtoneContent());
        // 将生成的URL设置到campusRingtone1对象的铃声路径属性中
        campusRingtone1.setRingtonePath(url);
        // 保存或更新修改后的campusRingtone1对象到数据库中
        saveOrUpdate(campusRingtone1);
        // 再次调用mapper的selectRingtoneByRingPeriod方法，获取更新后的campusRingtone对象
        CampusRingtone campusRingtone2 = campusRingtoneMapper.selectRingtoneByRingPeriod(campusRingtone);
        // 使用BeanUtil工具类将更新后的campusRingtone2的属性复制到campusRingtoneDTO中
        BeanUtil.copyProperties(campusRingtone2, campusRingtoneDTO);
        // 返回填充了更新后属性的campusRingtoneDTO对象
        return campusRingtoneDTO;
    }
}